﻿using System;
using System.Linq.Expressions;
using System.Reflection;

namespace Lync.Widget.Library.Extensions
{
    public static class ExpressionExtensions
    {
        public static void SetProperty<T, T1>(this Expression<Func<T, T1>> expression, object obj, object value)
        {
            try
            {
                ((PropertyInfo)(GetMemberExpression(expression).Member)).SetValue(obj, value, null);
            }
            catch (Exception ex)
            {
                throw new Exception(expression.ToString(), ex);
            }
        }

        public static TResult GetPropertyValue<T, TResult>(this T entity, string propertyName)
        {
            return (TResult)typeof(T).GetProperty(propertyName).GetValue(entity, null);
        }

        public static void SetPropertyValue<T>(this T entity, string propertyName, object value)
        {
            var prop = typeof (T).GetProperty(propertyName);
            prop.SetValue(entity, value, null);
        }

        public static string GetPropertyName<T, T1>(this Expression<Func<T, T1>> expression)
        {
            return GetMemberExpression(expression).Member.Name;
        }

        public static Type GetPropertyType<T, T1>(this Expression<Func<T, T1>> expression)
        {
            return GetMemberExpression(expression).Type;
        }

        public static MemberExpression GetMemberExpression<T, T1>(this Expression<Func<T, T1>> expression)
        {
            switch (expression.Body.NodeType)
            {
                case ExpressionType.MemberAccess:
                    return ((MemberExpression)(expression.Body));

                case ExpressionType.Call:
                    return ((MemberExpression)(((MethodCallExpression)(expression.Body)).Object));

                default:
                    return ((MemberExpression)(((UnaryExpression)(expression.Body)).Operand));
            }
        }
    }
}